// 高德地图
// main.js中引入
import VueAMap from 'vue-amap'
VueAMap.initAMapApiLoader({
  key: '24307c8a47a5a1a9c68b55b4d8c02356',
  plugin: ['AMap.Map','AMap.MouseTool','mouseTool.polygon','AMap.Polygon','AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],  // 默认高德 sdk 版本为 1.4.4
  v: '1.4.4'
});
或者
// index.html中引入
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=24307c8a47a5a1a9c68b55b4d8c02356&plugin=AMap.Geocoder&plugin&plugin=AMap.Autocomplete&plugin=AMap.PlaceSearch&plugin=AMap.PolyEditor&plugin=AMap.MouseTool"></script>

// 组件
<template>
<el-dialog
    center
    append-to-body
    title="地图选址"
    width="70%"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose">
      <div class="select-map">
        <div class="but">
          <div>
            <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          </div> 
          <div>
            <el-button @click="drawPolygon">开始绘制</el-button>
            <el-button @click="clearPolygon">清空当前绘制</el-button>
            <el-button @click="closeDrawPolygon">结束绘制并保存</el-button>
            <span style="font-size:10px;">&nbsp;&nbsp;&nbsp;&nbsp;小提示：右键取消</span>
          </div>

        </div>
        
        <div id="select-map"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

</template>
<script>
export default {
  data() {
    return {
      dialogVisible: true,
      map: {}, //保存地图对象
      mouseTool: {}, // 鼠标多边形绘制工具
      polyType: {
        borderColor: "",
        fillOpacity: 0.5,
        fillColor: "#000"
      },
      searchOption: {
        city: '',
        citylimit: true
      },
      center: [117.148118, 36.660223],
      markers: {
        position: []
      },
      polygonList: [], // 绘制图的点
      savePolygon: [] // 保存点
    };
  },
  mounted() {
    this.searchAddressMethod()
  },
  methods: {
    // 创建地图
    createMap() {
      let that = this;
      this.$nextTick(() => {
        //地图加载
        that.map = new AMap.Map("select-map", {
          zoom: 13,
          // layers: [new AMap.TileLayer.Satellite()], // 3d实物地图
          center: that.center
        });
        // 地图上打印当前的鼠标点击点位
        that.map.on("click", function(e) {
          console.log(e.lnglat.getLng() + "," + e.lnglat.getLat());
        });
        // 限制地图使用范围
       //  this.setLimit();
      });
    },
    // 限制地图显示范围
    // setLimit() {
    //   var bounds = this.map.getBounds();
    //   this.map.setLimitBounds(bounds);
    // },
    // 搜索
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let {lng, lat} = poi;
          lngSum += lng;
          latSum += lat;
          // this.markers[0].position.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.center = [center.lng, center.lat];
        console.log(this.center)
        this.createMap()
      }
    },
    // 绘制多边形
    drawPolygon() {
      if(this.polygonList.length >0){
        this.$message.error("围栏已存在!")
        return
      }
      let that = this;
      this.mouseTool = new AMap.MouseTool(this.map);
      this.mouseTool.polygon({
        strokeColor: this.polyType.borderColor,
        fillColor: this.polyType.fillColor,
        fillOpacity: parseFloat(this.polyType.fillOpacity / 100)
        //同Polygon的Option设置
      });
      //监听draw事件可获取画好的覆盖物
      this.polygonList = [];
      this.mouseTool.on("draw", function(e) {
        that.polygonList.push(e.obj);
        console.log("绘制的多边形", that.polygonList);
      });
      // this.mouseTool.close()
  },
    // 清空地图上绘制的多边形
    clearPolygon() {
      this.map.remove(this.polygonList);
      this.polygonList = [];
    },
    // 结束绘制多边形
    closeDrawPolygon() { 
      this.mouseTool.close();
      let savePolygon = [];
      for (let i = 0; i < this.polygonList.length; i++) {
        console.log(this.polygonList[i].getOptions());
        let op = this.polygonList[i].getOptions();
        let routePath = [];
        op.path.forEach(item => {
          routePath.push([item.lng, item.lat]);
        });
        let savearr = {
          path: routePath,
          strokeColor: op.strokeColor,
          strokeOpacity: op.strokeOpacity,
          fillOpacity: op.fillOpacity,
          fillColor: op.fillColor,
          zIndex: op.zIndex
        };
        this.savePolygon.push(savearr);
      }
      let save = JSON.stringify(this.savePolygon);
      console.log("savePolygon", save);
      sessionStorage.setItem("savePolygon", save);
      console.log(this.savePolygon[0].path);

      // 二维数组转对象
      let maplist=this.savePolygon[0].path.map((item,index)=>{
         var mapData={};
         mapData.lat = item[0];
         mapData.lng = item[1];
         return mapData
      })
      console.log(maplist)
    }
  },
  mounted() {
    this.createMap();
  }
};
</script>
<style lang="scss" scoped>
.select-map {
  width: 100%;
  height: 60vh;
  position: relative;
  .but {
    width: 95%;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 10px 20px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 78;
    background: rgba(0,0,0,0.5);
    span {
      color: #fff;
    }
  }
  #select-map {
    width: 100%;
    height: 100%;
  }
}


</style>